package com.wan37.auth.server;

import com.wan37.auth.component.AuthWorkerHandlerCenter;
import com.wan37.auth.global.HandlerManager;
import com.wan37.auth.handler.AuthServerHandler;
import com.wan37.protobuf.ParseRegistryMap;
import com.wan37.protobuf.codec.ProtoPacketDecoder;
import com.wan37.protobuf.codec.ProtoPacketEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * Auth认证服务器.
 *
 * @author : luoyong
 * @date : 2020-05-27 18:08
 **/
public class AuthServer implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(AuthServer.class);

    private int port;   //authServer的端口号

    private AuthWorkerHandlerCenter authWorkerHandlerCenter;  //认证中心


    @Override
    public void run() {

        startAuthServer();

    }


    private void startAuthServer() {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                        ChannelPipeline pipeline = ch.pipeline();

                        //LengthFieldBasedFrameDecoder
                        pipeline.addLast("LengthFieldBasedFrameDecoder",
                                new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,
                                        0,
                                        4,
                                        4,
                                        0));

                        pipeline.addLast("ProtobufPacketDecoder", new ProtoPacketDecoder());    //解码器
                        pipeline.addLast("AuthServerHandler", new AuthServerHandler(authWorkerHandlerCenter));
                        pipeline.addLast("ProtobufPacketEncoder", new ProtoPacketEncoder());    //编码器
                    }
                });

        //绑定端口, 启动连接
        ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(this.port));
        future.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {

                if (future.isSuccess()) {
                    //初始化
                    ParseRegistryMap.initRegistry();    //初始化协议的解析器
                    HandlerManager.initMsgHandlers();   //初始化消息的处理器
                    logger.info("[AuthServer] 成功启动，等待连接...");
                } else {
                    logger.info("[AuthServer] 启动失败。");
                }
            }
        });

    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public AuthWorkerHandlerCenter getAuthWorkerHandlerCenter() {
        return authWorkerHandlerCenter;
    }

    public void setAuthWorkerHandlerCenter(AuthWorkerHandlerCenter authWorkerHandlerCenter) {
        this.authWorkerHandlerCenter = authWorkerHandlerCenter;
    }
}